package com.bianmaba.batch.example.db.batch;

import com.bianmaba.batch.example.db.bean.Log;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @program: spring-batch-examples
 * @description:
 * @author: Chenjiabin
 * @create: 2019/1/8 11:35
 **/
@Configuration
@EnableBatchProcessing
public class BatchConfig {
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private CsvItemProcessor csvItemProcessor;
    @Autowired
    private LogReader logReader;
    @Autowired
    private LogWriter logWriter;

    @Bean
    public Job processJob() {
        return jobBuilderFactory.get("processJob")
                .incrementer(new RunIdIncrementer()).listener(listener())
                .flow(orderStep1()).end().build();
    }

    @Bean
    public Step orderStep1() {
        return stepBuilderFactory.get("orderStep1")
                //数据积累到一定数据后再写入数据
                .<Log, Log>chunk(100)
                .reader(logReader).processor(csvItemProcessor)
                .writer(logWriter)
                //异常处理
                .faultTolerant()
                    //出现异常时忽略1次（如果出现第二次则整个任务失败）
                    .skip(Exception.class)
                    .skipLimit(1)
                .build();
    }

    @Bean
    public JobExecutionListener listener() {
        return new LogJobCompletionListener();
    }
}
